<template>
  <div class="order-selector">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.fiscale_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单日期" prop="orderDate">
        <el-date-picker clearable
          v-model="queryParams.orderDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 订单列表 -->
    <el-table 
      v-loading="loading" 
      :data="orderList" 
      @selection-change="handleSelectionChange"
      height="400"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderNo" width="150" />
      <el-table-column label="客户名称" align="center" prop="customerName" width="150" />
      <el-table-column label="订单日期" align="center" prop="orderDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="center" prop="totalAmount" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.totalAmount }} {{ scope.row.currency || 'USD' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总重量" align="center" prop="totalWeight" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.totalWeight }} KG</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fiscale_order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="报关状态" align="center" prop="customsStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fiscale_customs_status" :value="scope.row.customsStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="商品数量" align="center" prop="itemCount" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.orderItems ? scope.row.orderItems.length : 0 }} 个</span>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 已选订单统计 -->
    <div v-if="selectedOrders.length > 0" style="margin-top: 15px; padding: 10px; background-color: #f0f9ff; border-radius: 4px;">
      <span style="color: #409EFF; font-weight: bold;">
        已选择 {{ selectedOrders.length }} 个订单，
        总金额：{{ calculateTotalAmount() }} USD，
        总重量：{{ calculateTotalWeight() }} KG
      </span>
    </div>

    <!-- 操作按钮 -->
    <div style="margin-top: 20px; text-align: right;">
      <el-button @click="handleCancel">取消</el-button>
      <el-button 
        type="primary" 
        :disabled="selectedOrders.length === 0"
        @click="handleConfirm"
      >确认选择({{ selectedOrders.length }})</el-button>
    </div>
  </div>
</template>

<script>
import { listOrder } from "@/api/fiscale/order";

export default {
  name: "OrderSelector",
  dicts: ['fiscale_order_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 订单列表
      orderList: [],
      // 已选订单
      selectedOrders: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        customerName: null,
        orderStatus: null,
        orderDate: null,
        // 添加过滤条件，排除已报关的订单
        customsStatus: 'not_declared' // 只显示未报关的订单
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.selectedOrders = selection;
    },

    /** 计算总金额 */
    calculateTotalAmount() {
      return this.selectedOrders.reduce((total, order) => {
        return total + (parseFloat(order.totalAmount) || 0);
      }, 0).toFixed(2);
    },

    /** 计算总重量 */
    calculateTotalWeight() {
      return this.selectedOrders.reduce((total, order) => {
        return total + (parseFloat(order.totalWeight) || 0);
      }, 0).toFixed(3);
    },

    /** 确认选择 */
    handleConfirm() {
      if (this.selectedOrders.length === 0) {
        this.$modal.msgWarning("请至少选择一个订单");
        return;
      }
      
      // 检查是否有已报关的订单
      const declaredOrders = this.selectedOrders.filter(order => 
        order.customsStatus === 'declared' || order.customsStatus === 'declaring');
      
      if (declaredOrders.length > 0) {
        const orderNos = declaredOrders.map(order => order.orderNo).join(', ');
        this.$modal.msgError(`以下订单已报关或正在报关中，不能重复报关: ${orderNos}`);
        return;
      }
      
      this.$emit('confirm', this.selectedOrders);
    },

    /** 取消选择 */
    handleCancel() {
      this.$emit('cancel');
    }
  }
}
</script>

<style scoped>
.order-selector {
  padding: 20px;
}
</style>